<?php

namespace app\controller;

use app\BaseController;
use DateTime;
use think\facade\Request;
use think\facade\Db;
use think\facade\Filesystem;

class Book extends BaseController {
    // GET $query
    public function fetchlook() {
        $result = [
            "status" => true,
            "collection" => []
        ];

        $query = Request::get("query");

        if ($query != null) {
            $find_result = Db::table("ZZZ_book_info")
            ->where("state", 1)
            ->whereLike("bookName|author|course", '%'. $query . '%')
            ->order('timestamp', 'desc')
            ->select()->toArray();
        } else {
            $find_result = Db::table("ZZZ_book_info")
            ->where("state", 1)
            ->order('timestamp', 'desc')
            ->select()->toArray();
        }

        if($find_result != []) {
            foreach ($find_result as $find_book_key => $find_book) {
                // 处理imageId和时间戳
                $now_bookId = $find_book["bookId"];
                $image_result = Db::table("ZZZ_book_image")
                                ->where("bookId", $now_bookId)
                                ->where("valid", 1)
                                ->order("timestamp")
                                ->column("imageId");
                $find_result[$find_book_key]["imageId"] = $image_result;

                $timestamp_datetime = new DateTime($find_book["timestamp"]);
                $timestamp_integer = $timestamp_datetime->getTimestamp();
                $find_result[$find_book_key]["timestampInteger"] = $timestamp_integer;
            }
        }

        $result["collection"] = $find_result;

        return json($result);
    }

    // GET $userId
    public function fetchsell() {
        $result = [
            "status" => false,
            "description" => "未知错误",
            "collection" => []
        ];

        $userId = Request::get("userId");

        if($userId != null) {
            $result["status"] = true;
            $result["description"] = "success";

            $find_result = Db::table("ZZZ_book_info")
            ->where("state", ">", 0)
            ->where('userId', $userId)
            ->order('timestamp', 'desc')
            ->select()->toArray();

            if($find_result != []) {
                foreach ($find_result as $find_book_key => $find_book) {
                    // 处理imageId、tradeNumber和时间戳
                    $now_bookId = $find_book["bookId"];
                    $image_result = Db::table("ZZZ_book_image")
                                    ->where("bookId", $now_bookId)
                                    ->where("valid", 1)
                                    ->order("timestamp")
                                    ->column("imageId");
                    $find_result[$find_book_key]["imageId"] = $image_result;

                    $trade_result = Db::table("ZZZ_trade_info")
                                    ->where("bookId", $now_bookId)
                                    ->count();
                    $find_result[$find_book_key]["tradeCount"] = $trade_result;

                    $timestamp_datetime = new DateTime($find_book["timestamp"]);
                    $timestamp_integer = $timestamp_datetime->getTimestamp();
                    $find_result[$find_book_key]["timestampInteger"] = $timestamp_integer;
                }
            }

            $result["collection"] = $find_result;
        } else {
            $result["description"] = "请求出错";
        }

        return json($result);
    }

    // GET $code
    public function fetchcode() {
        $result = [
            "status" => false,
            "description" => "未知错误",
            "bookName" => "",
            "author" => "",
            "course" => ""
        ];

        $code = Request::get("code");

        if($code != null) {
            $find_result = Db::table("ZZZ_book_code")
            ->where('code', $code)
            ->find();

            if($find_result != null) {
                $result["status"] = true;
                $result["description"] = "success";

                $result["bookName"] = $find_result["bookName"];
                $result["author"] = $find_result["author"];
                $result["course"] = $find_result["course"];
            } else {
                $result["description"] = "无此条形码信息";
            }
        } else {
            $result["description"] = "请求出错";
        }

        return json($result);
    }

    // POST $userId
    public function addbook() {
        $result = [
            "status" => false,
            "description" => "未知错误",
            "bookId" => ""
        ];

        $userId = Request::post("userId");

        if($userId != null) {
            $unique_bookId = "B" . uniqid();
            
            $add_book_result = Db::table("ZZZ_book_info")->insert([
                "bookId" => $unique_bookId,
                "userId" => $userId
            ]);

            if($add_book_result == 1) {
                $result["status"] = true;
                $result["description"] = "success";

                $result["bookId"] = $unique_bookId;
            }
        } else {
            $result["description"] = "请求出错";
        }

        return json($result);
    }
    
    // POST $bookId
    public function deletebook() {
        $result = [
            "status" => false,
            "description" => "未知错误"
        ];

        $bookId = Request::post("bookId");
  
        if($bookId != null){
            $result["status"] = true;
            $result["description"] = "success";
        
            Db::table("ZZZ_book_info")
            ->where("bookId", $bookId)
            ->delete();

            Db::table("ZZZ_book_image")
            ->where("bookId", $bookId)
            ->delete();

            Db::table("ZZZ_trade_info")
            ->where("bookId", $bookId)
            ->delete();
        } else {
            $result["description"] = "请求出错";
        }

        return json($result);
    }

    // POST $bookId + Others
    public function modifybook() {
        $result = [
            "status" => false,
            "description" => "未知错误"
        ];

        $bookId = Request::post("bookId");

        $newbookName = Request::post("bookName");
        $newTag = Request::post("tag");
        $newrequirePrice = Request::post("requirePrice");

        $newAuthor = Request::post("author");
        $newCourse = Request::post("course");
        $newDescription = Request::post("description");
         
        if($bookId != null){
            $result["status"] = true;
            $result["description"] = "success";
            
            if($newbookName != null) {
                Db::table("ZZZ_book_info")
                ->where("bookId", $bookId)
                ->update(["bookName" => $newbookName]);
            }

            if($newTag != null) {
                Db::table("ZZZ_book_info")
                ->where("bookId", $bookId)
                ->update(["tag" => $newTag]);
            }

            if($newrequirePrice != null) {
                Db::table("ZZZ_book_info")
                ->where("bookId", $bookId)
                ->update(["requirePrice" => $newrequirePrice]);
            }

            if($newAuthor != null) {
                Db::table("ZZZ_book_info")
                ->where("bookId", $bookId)
                ->update(["author" => $newAuthor]);
            }

            if($newCourse != null) {
                Db::table("ZZZ_book_info")
                ->where("bookId", $bookId)
                ->update(["course" => $newCourse]);
            }

            if($newDescription != null) {
                Db::table("ZZZ_book_info")
                ->where("bookId", $bookId)
                ->update(["description" => $newDescription]);
            }
        } else {
            $result["description"] = "请求出错";
        }

        return json($result);
    }

    // POST $bookId $state
    public function modifystate() {
        $result = [
            "status" => false,
            "description" => "未知错误"
        ];

        $bookId = Request::post("bookId");
        $newState = Request::post("state");
        
        if($bookId != null && $newState != null){
            $result["status"] = true;
            $result["description"] = "success";

            Db::table("ZZZ_book_info")
            ->where("bookId", $bookId)
            ->update(["state" => $newState]);
        } else {
            $result["description"] = "请求出错";
        }

        return json($result);
    }

    // POST
    // GET $bookId
    // FILE(POST) $bookImage
    public function uploadimage() {
        $result = [
            "status" => false,
            "description" => "未知错误",
            "imageId" => "",
            "imageAddress" => ""
        ];

        $bookId = Request::get("bookId");
        $file = Request::file('bookImage');

        if($bookId != null && $file != null) {
            $unique_imageId = "I" . uniqid();

            Filesystem::disk("public")->putFileAs("bookImage", $file, $unique_imageId . ".jpeg");

            $db_insert_result = Db::table("ZZZ_book_image")->insert([
                "imageId" => $unique_imageId,
                "bookId" => $bookId
            ]);

            if($db_insert_result == 1) {
                $result["status"] = true;
                $result["description"] = "success";
                $result["imageId"] = $unique_imageId;
            }
        } else {
            $result["description"] = "上传请求出错";
        }
        
        return json($result);
    }

    // POST $imageId
    public function lazydeleteimage() {
        $result = [
            "status" => false,
            "description" => "未知错误",
            "imageId" => ""
        ];

        $imageId = Request::post("imageId");

        if($imageId != null) {
            $result["status"] = true;
            $result["description"] = "success";
            $result["imageId"] = $imageId;

            Db::table("ZZZ_book_image")
            ->where("imageId", $imageId)
            ->update(["valid" => 0]);
        } else {
            $result["description"] = "请求出错";
        }
        
        return json($result);
    }
}
